package com.junlong0716.enjoylearning.service

import android.app.IntentService
import android.content.Intent
import android.os.Environment
import com.junlong0716.enjoylearning.entity.rxevent.DownloadSucceedEvent
import com.junlong0716.enjoylearning.entity.rxevent.ProgressEvent
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import java.io.File

/**
 *@author: EdsionLi
 *@description:
 *@date: Created in 2018/6/22 上午10:46
 *@modified by:
 */
class FileDownloadService : IntentService("FileDownloadService") {
    private val path = Environment.getExternalStorageDirectory().absolutePath + File.separator + "享学知识缓存文件" + File.separator

    override fun onHandleIntent(intent: Intent?) {
        val fileUrl = intent!!.getStringExtra("FILE_URL")
        val fileName = intent.getStringExtra("FILE_NAME")
        val fileId = intent.getIntExtra("FILE_ID",0)
        OkGo.get<File>(fileUrl)
                .tag(this)
                .execute(object : FileCallback(path, fileName) {
                    override fun onSuccess(response: Response<File>?) {
                        val file = response!!.body()
                        RxBus.getDefault().post(DownloadSucceedEvent(file,fileId))
                    }

                    override fun downloadProgress(progress: Progress?) {
                        RxBus.getDefault().post(ProgressEvent(progress!!,fileId))
                    }
                })
    }
}